package com.steptime.designpattern.creational.simplefactory;

public class RuleConfigSource {

    public RuleConfig load(String ruleConfigFilePath) throws InvalidRuleConfigException{
        IRuleConfigParser parser = createParser(ruleConfigFilePath);
        RuleConfig ruleConfig = parser.parse(ruleConfigFilePath);
        return ruleConfig;
    }

    private IRuleConfigParser createParser(String ruleConfigFilePath) throws InvalidRuleConfigException {
        IRuleConfigParser parser = null;
        String ruleConfigFileExtension = getFileExtension(ruleConfigFilePath);
        if ("json".equalsIgnoreCase(ruleConfigFileExtension)) {
            parser = new JsonRuleParser();
        } else if ("xml".equalsIgnoreCase(ruleConfigFileExtension)) {
            parser = new XmlRuleParser();
        } else if ("yaml".equalsIgnoreCase(ruleConfigFileExtension)) {
            parser = new YamlRuleParser();
        }else{
            throw new InvalidRuleConfigException("Rule config file format is not supported:"
                    + ruleConfigFilePath);
        }
        return parser;
    }

    private String getFileExtension(String ruleConfigFilePath) {
        return ruleConfigFilePath.substring(
                ruleConfigFilePath.lastIndexOf(".")+1,ruleConfigFilePath.length());
    }
}
